﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Minio;
using Minio.DataModel.Args;
using Minio.Exceptions;
using System;
using System.Drawing.Imaging;
using Traceability.App.InfrasIntructure;
using Traceability.App.Model;

namespace Traceability.App.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UploadsController : ControllerBase
    {
        private readonly IMinioClient _minioClient;
        private string bucketName = "img";
        private readonly TraceabilityDbContext _dbContext;

        public UploadsController(TraceabilityDbContext dbContext)
        {
            _minioClient = new MinioClient()
               .WithEndpoint("10.223.8.23:9000")
               .WithCredentials("admin", "admin123")
               .WithSSL(false)
               .Build();
            _dbContext = dbContext;
        }
        /// <summary>
        /// 列出所有桶
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ListBuckets()
        {
            var buckets = await _minioClient.ListBucketsAsync().ConfigureAwait(false);
            return Ok(buckets);
        }
        [HttpPost]
        public async Task<IActionResult> UploadFiles(IFormFileCollection formFiles)
        {
            // 获取请求头中的参数
            var batch = Request.Headers["Batch"].ToString();
            var imgType = Request.Headers["ImgType"].ToString();

            // 验证参数
            if (string.IsNullOrEmpty(batch) || string.IsNullOrEmpty(imgType))
            {
                return BadRequest("Batch和ImgType参数不能为空");
            }

            
            var beArgs = new BucketExistsArgs().WithBucket(bucketName);
            bool found = await _minioClient.BucketExistsAsync(beArgs);
            if (!found)
            {
                var mbArgs = new MakeBucketArgs().WithBucket(bucketName);
                await _minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);
            }

            var formFileList = new List<string>();
            foreach (var formFile in formFiles)
            {
                using var stream = formFile.OpenReadStream();
                var objectName = formFile.FileName;
                formFileList.Add(objectName);

                var putArgs = new PutObjectArgs()
                   .WithBucket(bucketName)
                   .WithObject(objectName)
                   .WithStreamData(stream)
                   .WithContentType(formFile.ContentType)
                   .WithObjectSize(stream.Length);
                await _minioClient.PutObjectAsync(putArgs).ConfigureAwait(false);

                var url = $"http://10.223.8.23:9000/{bucketName}/{objectName}";
                formFileList.Add(url);

                // 保存到数据库
                var imageInfo = new newPictureModel
                {
                    Batch = batch,
                    ImgType = imgType, // 前端传递的通用类型
                    ImgUrl = url,
                    IsDeleted = false
                };
                _dbContext.pictureModelsNew.Add(imageInfo);
            }

            await _dbContext.SaveChangesAsync();
            return Ok(formFileList);
        }

        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> DeleteImage(int id, [FromQuery] string imgType)
        {
            // 1. 从数据库查询图片信息
            var imageInfo = await _dbContext.pictureModelsNew
            .FindAsync(id);

            if (imageInfo == null || imageInfo.ImgType != imgType)
            {
                return NoContent();
            }
            if (imageInfo.ImgType != imgType)
            {
                return BadRequest("图片类型不匹配");
            }
            // 2. 解析MinIO对象名称
            var objectName = Path.GetFileName(imageInfo.ImgUrl);
            if (string.IsNullOrEmpty(objectName))
            {
                return BadRequest("无效的图片URL");
            }

            // 3. 开始数据库事务
            using var transaction = await _dbContext.Database.BeginTransactionAsync();

            try
            {
                // 4. 删除MinIO对象
                var args = new RemoveObjectArgs()
                   .WithBucket(bucketName)
                   .WithObject(objectName);

                await _minioClient.RemoveObjectAsync(args);

                // 5. 删除数据库记录
                _dbContext.pictureModelsNew.Remove(imageInfo);
                await _dbContext.SaveChangesAsync();

                // 6. 提交事务
                await transaction.CommitAsync();

                return NoContent();
            }
            catch (MinioException ex)
            {
                // 回滚事务
                await transaction.RollbackAsync();


                // 返回友好错误信息
                return StatusCode(500, "删除文件时发生错误，请稍后重试");
            }
            catch (Exception ex)
            {
                // 回滚事务
                await transaction.RollbackAsync();

               

                // 返回友好错误信息
                return StatusCode(500, "处理请求时发生内部错误");
            }
        }



        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetImagesByBatchAndType(
    [FromQuery] string batch,
    [FromQuery] string imgType)
        {
            // 1. 参数验证
            if (string.IsNullOrEmpty(batch) || string.IsNullOrEmpty(imgType))
            {
                return BadRequest("Batch和ImgType参数不能为空");
            }

            // 2. 查询数据库
            var images = await _dbContext.pictureModelsNew
                .Where(i => i.Batch == batch && i.ImgType == imgType && !i.IsDeleted)
                .ToListAsync();



            return Ok(images ?? new List<newPictureModel>());
        }

      
        ///// <summary>
        ///// 上传多个文件
        ///// </summary>
        ///// <param name="formFiles"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<IActionResult> UploadFiles(IFormFileCollection formFiles)
        //{
        //    var beArgs = new BucketExistsArgs().WithBucket(bucketName);
        //    bool found = await _minioClient.BucketExistsAsync(beArgs);
        //    if (!found)
        //    {
        //        var mbArgs = new MakeBucketArgs().WithBucket(bucketName);
        //        await _minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);
        //    }
        //    var formFileList = new List<string>();
        //    foreach (var formFile in formFiles)
        //    {
        //        using var stream = formFile.OpenReadStream();
        //        var objectName = formFile.FileName;
        //        formFileList.Add(objectName);
        //        var putArgs = new PutObjectArgs()
        //            .WithBucket(bucketName)
        //            .WithObject(objectName)
        //            .WithStreamData(stream)
        //            .WithContentType(formFile.ContentType)
        //            .WithObjectSize(stream.Length);
        //        await _minioClient.PutObjectAsync(putArgs).ConfigureAwait(false);
        //        var url = $"http://10.223.8.23:9000/{bucketName}/{objectName}";
        //        formFileList.Add(url);
        //    }
        //    return Ok(formFileList);
        //}
    }
}
